//
//  UploadHandler.swift
//  Upload
//
//  Created by Wei Zhang on 2022/2/14.
//

import ReplayKit

class UploadHandler: RPBroadcastSampleHandler {
    
    var assetWriter : AVAssetWriter!
    var videoInput : AVAssetWriterInput!
    var audioInput : AVAssetWriterInput!
    var micAudioInput : AVAssetWriterInput!
    
    var tool : DSUploadTool?
    
    override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) {
        // User has requested to start the broadcast. Setup info from the UI extension can be supplied but optional.
        URLSession.shared.dataTask(with: URLRequest.init(url: URL.init(string: "https://www.baidu.com")!))
        tool = DSUploadTool.shared
        tool?.prefareToStart(setupInfo ?? [:])
    }
    
    override func broadcastPaused() {
        // User has requested to pause the broadcast. Samples will stop being delivered.
    }
    
    override func broadcastResumed() {
        // User has requested to resume the broadcast. Samples delivery will resume.
    }
    
    override func broadcastFinished() {
        // User has requested to finish the broadcast.
        //录屏结束
        tool?.stop()
    }
    
    override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
        DispatchQueue.main.async {
            switch sampleBufferType {
            case RPSampleBufferType.video:
                // Handle video sample buffer
                print("video###:\(sampleBuffer)")
                self.tool?.sendVideoBuffer(sampleBuffer)
                break
            case RPSampleBufferType.audioApp:
                print("audio###:\(sampleBuffer)")
                // Handle audio sample buffer for app audio
//                self.tool?.sendAudioBuffer(sampleBuffer)
                AgoraAudioTube.pushAudioCMSampleBuffer(sampleBuffer, resampleRate: 44100, type: .app)
                break
            case RPSampleBufferType.audioMic:
                print("audioMic###:\(sampleBuffer)")
//                self.tool?.sendAudioBuffer(sampleBuffer)
                // Handle audio sample buffer for mic audio
                AgoraAudioTube.pushAudioCMSampleBuffer(sampleBuffer, resampleRate: 48000, type: .mic)
                break
            @unknown default:
                // Handle other sample buffer types
                fatalError("Unknown type of sample buffer")
            }
        }
        
    }
    
   
}

